package com.freesky.biz.icbc.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.freesky.biz.icbc.domain.TPartnership;
import com.freesky.biz.icbc.domain.TPensionUser;
import com.freesky.biz.icbc.excel.TPartnershipImport;
import com.freesky.biz.icbc.excel.TPensionUserImport;
import com.freesky.biz.icbc.mapper.PartnershipMapper;
import com.freesky.biz.icbc.mapper.PensionUserMapper;
import com.freesky.biz.icbc.service.IPartnershipService;
import com.freesky.biz.icbc.service.IPensionUserService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.constant.HttpStatus;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.enums.ExportStatusEnum;
import com.freesky.common.exception.CustomException;
import com.freesky.common.utils.DateUtils;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.ServletUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.file.FileDownloadUtils;
import com.freesky.common.utils.poi.ExcelUtil;
import com.freesky.system.domain.TExportRecord;
import com.freesky.system.domain.TImportRecord;
import com.freesky.system.service.ITExportRecordService;
import com.freesky.system.service.ITImportRecordService;
import com.freesky.system.task.SyncReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PensionUserServiceImpl implements IPensionUserService {

    private static final Logger logger = LoggerFactory.getLogger(PensionUserServiceImpl.class);

    @Autowired
    private PensionUserMapper pensionUserMapper;

    @Autowired
    private ITExportRecordService exportRecordService;

    @Autowired
    private ITImportRecordService importRecordService;

    @Autowired
    private SyncReport syncReport;

    @Value("${model.cover}")
    private String coverPath;


    @Override
    public List<TPensionUser> findList(TPensionUser pensionUser) {
        return pensionUserMapper.findList(pensionUser);
    }

    @Override
    public AjaxResult exportFile(TPensionUser pensionUser) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        TExportRecord exportRecord = new TExportRecord();
        exportRecord.setId(SeqUtil.getSeqId());
        exportRecord.setBizType("PENSION_USER");
        exportRecord.setCreateBy(String.valueOf(sysUser.getUserId()));

        TExportRecord exportRecordSelect = exportRecordService.selectRecordExportByStatus(exportRecord);
        if (exportRecordSelect != null) {
            return AjaxResult.error("已经有下载任务");
        }

        exportRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());
        System.out.println(JSON.toJSONString(exportRecord));
        exportRecordService.insert(exportRecord);

        syncReport.exportFileMutilHeader(pensionUser, new TPensionUser(), IPensionUserService.class,
                "findList", "养老金",Long.parseLong(exportRecord.getId()),sysUser.getUserName());

        return AjaxResult.success();
    }

    @Override
    public AjaxResult exportExcel() {
        String fileName = "导入模板_养老金.xlsx";
        String path = coverPath + fileName;
        String downLoadName = new StringBuilder("导入模板_养老金_").append(DateUtils.dateTime()).append(".xlsx").toString();
        try {
            FileDownloadUtils.downloadLocal(path, downLoadName, ServletUtils.getRequest(), ServletUtils.getResponse());
            return AjaxResult.success(downLoadName);
        } catch (FileNotFoundException e) {
            logger.error("导出Excel异常:", e);
            throw new CustomException("导出Excel失败，请联系网站管理员！");
        }
    }

    @Override
    public AjaxResult importExcel(MultipartFile file){
        try {

            TImportRecord importRecord = new TImportRecord();
            String batchId = SeqUtil.getSeqId();
            importRecord.setRecordId(batchId);

            List<TPensionUserImport> excelList = EasyExcel.read(file.getInputStream()).head(TPensionUserImport.class).sheet().doReadSync();
            if(excelList==null || excelList.isEmpty()){
                throw new CustomException("Excel表格为空或解析失败");
            }

            List<TPensionUserImport> errorList = new ArrayList<>();
            for(int i=0;i<excelList.size();i++){
                TPensionUserImport pensionUserImport = excelList.get(i);
                pensionUserImport.setId(SeqUtil.getSeqId());
                pensionUserImport.setBatchId(batchId);

                if(StringUtils.isEmpty(pensionUserImport.getMobile())){
                    pensionUserImport.setRemarks("领取号码不能为空");
                    errorList.add(pensionUserImport);
                }
                excelList.set(i,pensionUserImport);
            }
            importRecord.setBizType("PENSION_USER");
            importRecord.setTotalRecord(Long.valueOf(excelList.size()));
            importRecord.setErrorRecord(Long.valueOf(errorList.size()));
            importRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());

            if(errorList.size()>0){
                ExcelUtil util = new ExcelUtil(TPensionUserImport.class);
                importRecord.setStatus(ExportStatusEnum.SUBMIT_FAIL.getValue());
                AjaxResult result = util.exportEasyExcel(errorList, "养老金-error");
                if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)) {
                    String exFileName = (String) result.get(AjaxResult.MSG_TAG);
                    // 异常文件名
                    importRecord.setExFileName(exFileName);
                    importRecord.setStatus(2L);
                }
                importRecordService.insertTImportRecord(file,importRecord);
                return result;
            } else {

                pensionUserMapper.batchAddList(excelList);

                importRecord.setStatus(ExportStatusEnum.SUBMIT_SUCCESS.getValue());
                importRecordService.insertTImportRecord(file,importRecord);
            }

        } catch (Exception ioe){
            throw new CustomException("解析Excel时发生错误", ioe);
        }
        return AjaxResult.success();
    }

}
